using System.Collections.Generic;
using System.Linq;
using CfgTable;
using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using UnityEngine.UI;

namespace IQIGame.Onigao.GamePlay
{
    public class UICollectItem : UIBaseWindow
    {
        #region CreateConfig

        /// <summary>
        /// 静态配置
        /// </summary>
        private static UICreateConfig _createConfig = new()
        {
            prefabName = nameof(UICollectItem),
            layer = EUILayer.Normal,
            activeBlurBg = true,
            blurDownSampling = 4,
        };

        /// <summary>
        /// 创建UI的配置
        /// </summary>
        public override IUICreateConfig createConfig => _createConfig;

        #endregion

        #region Template Generate,don't modify

        protected class UIB_UICollectItem
        {
            #region ObjectBinding Generate

            public ExButton btnClose { protected set; get; }
            public ExButton btnGet { protected set; get; }
            public ExText curProgress { protected set; get; }
            public ExText desc { protected set; get; }
            public ExButton btnMask { protected set; get; }
            public ExLoopHorizontalScrollRect scrollRect { protected set; get; }

            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<ExButton>("btnClose", out var __tbv0);
                btnClose = __tbv0;
                __binding.TryGetVariableValue<ExButton>("btnGet", out var __tbv1);
                btnGet = __tbv1;
                __binding.TryGetVariableValue<ExText>("curProgress", out var __tbv2);
                curProgress = __tbv2;
                __binding.TryGetVariableValue<ExText>("desc", out var __tbv3);
                desc = __tbv3;
                __binding.TryGetVariableValue<ExButton>("btnMask", out var __tbv4);
                btnMask = __tbv4;
                __binding.TryGetVariableValue<ExLoopHorizontalScrollRect>("scrollRect", out var __tbv5);
                scrollRect = __tbv5;
            }

            #endregion ObjectBinding Generate
        }

        protected UIB_UICollectItem ui { get; set; }

        #endregion Template Generate,don't modify

        #region Field

        private int completePhase => _curPhase.Progress <= _curProgress ? _curPhase.Phase : _curPhase.Phase - 1;
        private CfgQuestPhase _curPhase;
        private int _curProgress;

        private List<CfgQuestPhase> _phases;

        private LoopScrollAdapter<UIN_QuestPhase> _phaseList;

        #endregion

        #region Override

        protected override void BeforeInit()
        {
            ui = new UIB_UICollectItem();
            ui.InitBinding(csObjBind);
        }

        protected override void OnInit()
        {
            _phases = ListPool<CfgQuestPhase>.Get();
            InitPhasesAndProgress();
            _phaseList = InitLoopScroll<UIN_QuestPhase>(ui.scrollRect, RefreshPhaseItem);
        }

        private void InitPhasesAndProgress()
        {
            var allCfg = TableCenter.questPhase.DataList;
            for (var i = 0; i < allCfg.Count; i++)
            {
                /*if (allCfg[i].QuestId == QuestModule.Instance.collectionQuestCid)
                {

                }*/
                _phases.Add(allCfg[i]);
            }

            _curProgress =
                GameDataCenter.PlayerData.quest.TryGetValue(QuestModule.Instance.collectionQuestCid, out var questData)
                    ? questData.progress
                    : 0;
            for (var i = 0; i < _phases.Count; i++)
            {
                if (_phases[i].Progress <= _curProgress) continue;
                _curPhase = _phases[i];
                break;
            }

            _curPhase ??= _phases.Last();
        }

        protected override void AddUGUIListener()
        {
            ui.btnClose.onClick.AddListener(OnBtnCloseClick);
            ui.btnMask.onClick.AddListener(OnBtnCloseClick);
        }

        protected override void OnShow(UIBaseData data)
        {
            _phaseList.RefillCells(_phases.Count);
            ui.desc.text = string.Format(_curPhase.DescFormat, _curProgress, _curPhase.Progress);
            ui.curProgress.text = $"{_curProgress.ToString()}/{_curPhase.Progress}";
            InitBtnGet();
        }

        protected override void OnHide()
        {
        }

        protected override void OnDispose()
        {
            ListPool<CfgQuestPhase>.Put(_phases);
            _phases = null;
        }

        #endregion

        #region Method

        private void RefreshPhaseItem(UIN_QuestPhase item, int index)
        {
            var phase = _phases[index];
            var prevProgress = index > 0 ? _phases[index - 1].Progress : 0;
            item.Refresh(phase, _curProgress, prevProgress);
        }

        private void OnBtnCloseClick()
        {
            Close();
        }

        private void InitBtnGet()
        {
            if (!GameDataCenter.PlayerData.quest.TryGetValue(QuestModule.Instance.collectionQuestCid,
                    out var questData))
            {
                ui.btnGet.SetActive(false);
                return;
            }

            var gotPhase = questData.rewardPhase;
            if (completePhase == 0 || completePhase <= gotPhase)
            {
                ui.btnGet.SetActive(false);
                return;
            }

            ui.btnGet.SetActive(true);
            ui.btnGet.onClick.AddListener(OnBtnGetClick);
        }

        private void OnBtnGetClick()
        {
            DoGetReward(QuestModule.Instance.collectionQuestCid, completePhase).Forget();
        }

        private async UniTaskVoid DoGetReward(int questId, int phase)
        {
            var result = await QuestModule.NetCore.CS_getPhaseReward(questId, phase);
            if (!result.IsSuccess)
            {
                return;
            }

            Close();
            NoticeModule.ShowUIItemGet(result.awards);
        }

        #endregion
    }
}